package com.cicdi.alayarobot.util;

import com.alaya.crypto.Credentials;
import com.alaya.parameters.NetworkParameters;
import com.alaya.protocol.Web3j;
import com.alaya.protocol.Web3jService;
import com.alaya.protocol.core.DefaultBlockParameterName;
import com.alaya.protocol.core.methods.response.PlatonGetTransactionCount;
import com.alaya.protocol.http.HttpService;

import java.io.IOException;
import java.math.BigInteger;

/**
 * nonce类工具
 *
 * @author haypo
 * @date 2020/12/1
 */
public class NonceUtil {

    /**
     * 获取钱包的nonce
     *
     * @param web3j       web3j对象
     * @param credentials 钱包
     * @return 当前的nonce值
     * @throws IOException web3j的io异常
     */
    public synchronized static BigInteger getNonce(Web3j web3j, Credentials credentials) throws IOException {
        String address = credentials.getAddress(NetworkParameters.CurrentNetwork.getChainId());
        PlatonGetTransactionCount count = web3j.platonGetTransactionCount(address, DefaultBlockParameterName.PENDING).send();
        if (count.getTransactionCount().intValue() == 0) {
            count = web3j.platonGetTransactionCount(
                    address, DefaultBlockParameterName.LATEST).send();
        }
        return count.getTransactionCount();
    }

    /**
     * 获取钱包的nonce
     *
     * @param nodeUrl     节点地址
     * @param credentials 钱包
     * @return 当前的nonce值
     * @throws IOException web3j的io异常
     */
    public synchronized static BigInteger getNonce(String nodeUrl, Credentials credentials) throws IOException {
        Web3j web3j = Web3j.build(new HttpService(nodeUrl));
        return getNonce(web3j, credentials);
    }

    /**
     * 获取钱包的nonce
     *
     * @param web3jService web3j service 对象
     * @param credentials  钱包
     * @return 当前的nonce值
     * @throws IOException web3j的io异常
     */
    public synchronized static BigInteger getNonce(Web3jService web3jService, Credentials credentials) throws IOException {
        return getNonce(Web3j.build(web3jService), credentials);
    }
}
